const moment = require('moment');
module.exports = (options, app) => {
  return async function(ctx, next) {

    let token = ctx.header.authorization;

    if (token) {
      try {
        token = token.replace('Bearer ', '');
        const user = ctx.app.jwt.verify(token, options.secret);

        if (user) {
          const origin_session = ctx.session;

          if (!origin_session.token) {
            ctx.status = 401;
            ctx.body = {
              code: 401,
              msg: 'failed',
              data: '未登录',
            };
            return;
          }
          if (moment(origin_session.ins).add(origin_session.exp, 's').isBefore(moment())) {
            throw new Error('403');
          }

          ctx.session.ins = moment().valueOf();

          await next();
        } else {
          ctx.status = 403;
          ctx.body = {
            code: 403,
            msg: 'failed',
            data: '授权到期',
          };
          return;
        }
      } catch (error) {
        ctx.status = 403;
        ctx.body = {
          code: 403,
          msg: 'failed',
          data: '授权到期',
        };
        return;
      }

    } else {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        msg: 'failed',
        data: '未授权',
      };
      return;
    }
  };
};
